import { useCallback, useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import styles from './dev.module.css';
import MpComponent from "./MpComponent";
import MetaPlatformForm from "./MpForm";
import MetaPlatformPage from "./MpPage";

export default function Dev(props) {
  const { name } = useParams();
  const [component, setComponent] = useState(null);

  const getMetadataURL = useCallback((fullname) => {
    const [pack_name, page_name] = fullname.split(':');
    return window[pack_name].metadata.get(page_name);
  }, []);

  useEffect(() => {
    if (!name) return;
    const searchParams = Object.fromEntries(new URLSearchParams(window.location.search));
    if (name.toLowerCase().endsWith('.mppage')) {
      const url = getMetadataURL(name);
      if (!url) return;
      fetch(url).then(async res => {
        const metadata = await res.json();
        setComponent(<div className={styles.dev}><MetaPlatformPage {...searchParams} metadata={metadata} /></div>);
      });
    } else if (name.toLowerCase().endsWith('.mpform')) {
      const url = getMetadataURL(name);
      if (!url) return;
      fetch(url).then(async res => {
        const metadata = await res.json();
        setComponent(<div className={styles.dev}><MetaPlatformForm {...searchParams} metadata={metadata} /></div>);
      });
    } else {
      setComponent(<div className={styles.dev}><MpComponent name={name} {...props} {...searchParams} /></div>);
    }
  }, [name, props, getMetadataURL]);

  return component;
}